<?php
namespace app\controller;

use think\Request;
use think\facade\Db;
use app\BaseController;
use think\facade\Config;

use Qiniu\Storage\UploadManager;
use Qiniu\Auth;

class Upload extends BaseController
{
	public function uploadPic(Request $request)
	{
		$arr = [];
	    $arr['url']     = '';
	    $arr['name']    = '';
	    $arr['error']   = '';
	    $arr['message'] = '';

		try {

			$accessKey = Config::get('filesystem.disks.qiniu.accessKey');
			$secretKey = Config::get('filesystem.disks.qiniu.secretKey');
			$bucket    = Config::get('filesystem.disks.qiniu.bucket');
			$url       = Config::get('filesystem.disks.qiniu.url');
			
			$file = request()->file('file');
            $savename = \think\facade\Filesystem::disk('public')->putFile( 'topic', $file);

            # 上传到存储后保存的文件名
            $key = str_replace('\\', '/', $savename);

            # 要上传文件的本地路径
            $filePath = Config::get('filesystem.disks.public.root').'/'.$savename;

            $uploadMgr = new UploadManager();

            $auth = new Auth($accessKey, $secretKey);
		    $token = $auth->uploadToken($bucket);

		    list($ret, $error) = $uploadMgr->putFile($token, $key, $filePath);

		    # 删除本地
		    @unlink($filePath);

		    if ($error !== null) {

		    	# 失败操作
		    	$arr['error']   = 1;
		    	$arr['message'] = $error;

		    	return json($arr);
		    }

		    # 成功操作
	    	$arr['url']     = $url.'/'.$key;
	    	$arr['error']   = 0;
	    	$arr['message'] = '上传成功';

	    	return json($arr);

        } catch (\Exception $e) {

        	$arr = [];
		    $arr['url']     = '';
		    $arr['name']    = '';
		    $arr['error']   = '';
		    $arr['message'] = '';
        	$arr['error']   = 1;
	    	$arr['message'] = $e->getMessage();

            // 这是进行异常捕获
            return json($arr);
        }
	}
}